#include "UdpListenerThread.h"
#include <QDebug>

UdpListenerThread::UdpListenerThread(quint16 port, QObject* parent)
    : QThread(parent), port(port), isRunning(false), udpSocket(nullptr)
{
}

void UdpListenerThread::startListening()
{
    if (!isRunning) {
        isRunning = true;
        start();
    }
}

void UdpListenerThread::stopListening()
{
    isRunning = false;
    if (udpSocket) {
        udpSocket->close();
    }
    wait();
}

void UdpListenerThread::run()
{
    udpSocket = new QUdpSocket();

    if (!udpSocket->bind(port, QUdpSocket::ShareAddress)) {
        emit statusMessage("UDP绑定失败: " + udpSocket->errorString());
        return;
    }

    emit statusMessage("UDP监听已启动，端口: " + QString::number(port));

    while (isRunning) {
        if (udpSocket->hasPendingDatagrams()) {
            QByteArray datagram;
            datagram.resize(udpSocket->pendingDatagramSize());

            QHostAddress senderAddr;
            quint16 senderPort;
            udpSocket->readDatagram(datagram.data(), datagram.size(),
                                  &senderAddr, &senderPort);

            QString command = QString::fromUtf8(datagram).trimmed();
            emit statusMessage("收到命令: " + command + " 来自: " +
                              senderAddr.toString() + ":" + QString::number(senderPort));
            emit commandReceived(command);
        }
        msleep(100);
    }

    udpSocket->close();
    delete udpSocket;
    udpSocket = nullptr;
}
